#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.shortcuts import render
from django.views.generic import View
from pure_pagination import Paginator, EmptyPage, PageNotAnInteger   # 分页功能
from django.http import HttpResponse
from django.db.models import Q

from .models import  CourseOrg, CityDict, Teacher
from operation.models import UserFavorite

from .forms import UserAskForm
from courses.models import Course

# Create your views here.


class OrgView(View):
    '''
    课程机构列表功能
    '''
    def get(self, request):
        # 课程机构
        all_orgs = CourseOrg.objects.all()
        # 授课机构排名  排序
        hot_orgs = all_orgs.order_by("-click_nums")[:3]

        # 城市
        all_citys = CityDict.objects.all()

        # 课程机构 全局搜索关键词
        # search_keywords = request.POST.get('keywords', "")   # POST不正确 是提交 现在是获取网址字符串 应使用get
        search_keywords = request.GET.get('keywords', "")
        if search_keywords:
            # 若keywords不为空 存在 则 进行过滤
            all_orgs = all_orgs.filter(Q(name__icontains=search_keywords)|Q(desc__icontains=search_keywords))
            # name__表示在name上进行操作  name__icontains 做like语句操作 ---加i表示 不区分大小写

        # 取出筛选城市
        city_id = request.GET.get('city',"")
        # 在结果集中进一步筛选
        if city_id :
            all_orgs = all_orgs.filter(city_id=int(city_id))  # 在过滤时可以直接用city_id

        # 类别筛选
        category = request.GET.get('ct',"")
        # 在结果集中进一步筛选
        if category :
            all_orgs = all_orgs.filter(category=category)  # 在过滤时可以直接用city_id 不必取外键
        # 排序
        sort = request.GET.get('sort','')
        if sort:
            if sort == "students":
                all_orgs = all_orgs.order_by("-students")  # 根据学习人数进行排名
            elif sort == "course":
                all_orgs = all_orgs.order_by("-course_nums")  # 根据课程数
         # 课程机构数目
        org_nums = all_orgs.count()  # 机构数目
        # 分页 对课程机构 看做对象然后进行分页
        try:
            # 生成页码时会自动加上page 无需做过多改动
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1

        # objects = ['john', 'edward', 'josh', 'frank']

        # Provide Paginator with the request object for complete querystring generation

        p = Paginator(all_orgs, 5, request=request)   # 每页显示5个

        orgs = p.page(page)

        return render(request, 'org-list.html', {
            'all_orgs':orgs,  # 就不会把所有课程机构传递过去   # 展示于模板页面中
            'all_citys':all_citys,
            'org_nums':org_nums,
            'city_id':city_id,  # 传发窗口前台进行比对 进而达到选中状态
            'category':category,
            'hot_orgs':hot_orgs,
            "sort":sort,
        })


# 增加用户咨询
class AddUserAskView(View):
    '''
    用户添加 咨询【我要学习】
    '''
    # 是异步操作 不会对整个页面进行刷新  是Ajax操作
    # 只有 表单 故只处理 post请求即可
    def post(self, request):
        user_ask_form = UserAskForm(request.POST)
        if user_ask_form.is_valid():
            # 区别 可以直接save 多了model的属性
            user_ask = user_ask_form.save(commit=True)  # 提交到数据库 并真正保存
            # 异步 不刷新当前页面 应当返回 json数据  此处用到 HttpResponse
            return HttpResponse('{"status":"success"}', content_type='application/json')  # 返回json字符串
        else:
            return HttpResponse('{"status":"fail","msg":"添加出现错误"}', content_type='application/json')  # 同时返回错因
        # 'msg':{0}}".format(user_ask_form.errors)



class OrgHomeView(View):
    '''
    关于课程机构详情页的设计  机构首页
    '''
    def get(self, request, org_id):
        current_page = "home"
        # 根据id取到课程机构
        course_org = CourseOrg.objects.get(id=int(org_id))
        # 点击课程机构 点击数＋1
        course_org.click_nums += 1
        course_org.save()

        has_fav = False   # 判断登录 收藏状态
        if request.user.is_authenticated():
            # 用户是否已经登录
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):  # 联合查询
                # 2表示课程机构
                has_fav = True

        # 反向取 如a的外键是b则 通过b取到a  有外键均可  使用 根据orm所处类的名称_set
        # 取出该机构所有课程
        all_courses = course_org.course_set.all()[:3]  # 取三个
        # print "all_courses:",all_courses
        # 教该课程的所有老师
        # 错因 太傻了 非常低级的错误 是属性 不是 方法
        # all_teachers = course_org.teacher_set().all()[:1]
        all_teachers = course_org.teacher_set.all()[:1]

        return render(request, 'org-detail-homepage.html',
                      {
                          'all_courses':all_courses,
                          'all_teachers':all_teachers,
                          'course_org':course_org,
                          'current_page':current_page,
                          'has_fav':has_fav,
                      }
                      )




class OrgCourseView(View):
    '''
    关于课程机构详情页的设计  机构课程
    '''
    def get(self, request, org_id):
        current_page = "course"  # 做 左侧标记使用
        # 根据id取到课程机构
        course_org = CourseOrg.objects.get(id=int(org_id))

        has_fav = False   # 判断登录 收藏状态
        if request.user.is_authenticated():
            # 用户是否已经登录
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):  # 联合查询
                # 2表示课程机构
                has_fav = True

        # 反向取 如a的外键是b则 通过b取到a  有外键均可  使用 根据orm所处类的名称_set
        # 取出该机构所有课程
        all_courses = course_org.course_set.all()
        # print "all_courses:",all_courses

        return render(request, 'org-detail-course.html',
                      {
                          'all_courses':all_courses,
                          'course_org':course_org,
                          'current_page':current_page,
                          'has_fav':has_fav,
                      }
                      )


class OrgDescView(View):
    '''
    关于课程机构详情页的设计  机构介绍
    '''
    def get(self, request, org_id):
        current_page = "desc"  # 做 左侧标记使用
        # 根据id取到课程机构
        course_org = CourseOrg.objects.get(id=int(org_id))

        has_fav = False   # 判断登录 收藏状态
        if request.user.is_authenticated():
            # 用户是否已经登录
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):  # 联合查询
                # 2表示课程机构
                has_fav = True

        return render(request, 'org-detail-desc.html',
                      {
                          'course_org':course_org,
                          'current_page':current_page,
                          'has_fav':has_fav,

                      }
                      )


class OrgTeacherView(View):
    '''
    关于课程机构详情页的设计  机构讲师
    '''
    def get(self, request, org_id):
        current_page = "teacher"  # 做 左侧标记使用
        # 根据id取到课程机构
        course_org = CourseOrg.objects.get(id=int(org_id))

        has_fav = False   # 判断登录 收藏状态
        if request.user.is_authenticated():
            # 用户是否已经登录
            if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):  # 联合查询
                # 2表示课程机构
                has_fav = True

        # 反向取 如a的外键是b则 通过b取到a  有外键均可  使用 根据orm所处类的名称_set
        # 取出该机构所有课程
        all_teachers = course_org.teacher_set.all()
        # print "all_courses:",all_courses

        return render(request, 'org-detail-teachers.html',
                      {
                          'all_teachers':all_teachers,
                          'course_org':course_org,
                          'current_page':current_page,
                          'has_fav':has_fav

                      }
                      )


class AddFavView(View):
    '''
    用户收藏 用户取消收藏   接口
    '''
    def post(self, request):
        fav_id = request.POST.get('fav_id', 0) # 默认为0 防止空字符串抛出异常
        fav_type = request.POST.get('fav_type', 0)
        # 用户收藏 或者 用户收藏删除
        # 先查询是否存在   ---再判断用户是否已经登录
        if not request.user.is_authenticated():   # 匿名的用户类 判断是否登录
            # 未登录 无法收藏  然后在ajax跳转至登录页面
            return HttpResponse('{"status":"fail","msg":"您还未登录"}', content_type='application/json')  # 同时返回错因
        exist_records = UserFavorite.objects.filter(user=request.user, fav_id=int(fav_id), fav_type=int(fav_type))  # 联合查询
        if exist_records:
            # 记录已经存在 表示用户要取消收藏
            exist_records.delete()  # 删除
            if int(fav_type) == 1:
                # 1 表示课程
                print '课程学习'
                course = Course.objects.get(id=int(fav_id))
                course.fav_nums -= 1  # 收藏数减去1
                if course.fav_nums < 0:
                    course.fav_nums = 0
                course.save()
            elif int(fav_type) == 2:
                course_org = CourseOrg.objects.get(id=int(fav_id))
                course_org.fav_nums -= 1
                if course_org.fav_nums < 0:
                    course_org.fav_nums = 0
                course_org.save()
            elif int(fav_type) == 3:
                teacher = Teacher.objects.get(id=int(fav_id))
                teacher.fav_nums -= 1
                if teacher.fav_nums < 0:
                    teacher.fav_nums = 0
                teacher.save()
            return HttpResponse('{"status":"success","msg":"收藏"}', content_type='application/json')  # 同时返回错因
            # return HttpResponse('{"status":"fail","msg":"收藏"}', content_type='application/json')  # 同时返回错因
        else:
            # 添加
            user_fav = UserFavorite()  # 创建类实例
            if int(fav_id) > 0 and int(fav_type) > 0:
                user_fav.user = request.user  # 填充字段
                user_fav.fav_id = int(fav_id)
                user_fav.fav_type = int(fav_type)
                user_fav.save()  # 存入数据库

                if int(fav_type) == 1:
                    # 1 表示课程
                    course = Course.objects.get(id=int(fav_id))
                    print '收藏。。', course.fav_nums
                    course.fav_nums += 1  # 收藏数1
                    print '收藏。。', course.fav_nums
                    course.save()
                    print 'ok'
                elif int(fav_type) == 2:
                    course_org = CourseOrg.objects.get(id=int(fav_id))
                    course_org.fav_nums += 1
                    course_org.save()
                elif int(fav_type) == 3:
                    teacher = Teacher.objects.get(id=int(fav_id))
                    teacher.fav_nums += 1
                    teacher.save()

                return HttpResponse('{"status":"success","msg":"已收藏"}', content_type='application/json')  # 同时返回错因
            else:
                return HttpResponse('{"status":"fail","msg":"收藏出现错误！"}', content_type='application/json')  # 同时返回错因


class TeacherListView(View):
    '''
    课程讲师列表页
    '''
    def get(self, request):
        # 取出所有的老师
        all_teachers = Teacher.objects.all()

        # 课程机构 全局搜索关键词
        # search_keywords = request.POST.get('keywords', "")   # POST不正确 是提交 现在是获取网址字符串 应使用get
        search_keywords = request.GET.get('keywords', "")
        if search_keywords:
            # 若keywords不为空 存在 则 进行过滤
            all_teachers = all_teachers.filter(Q(name__icontains=search_keywords)|
                                               Q(work_company__icontains=search_keywords)|
                                               Q(work_position__icontains=search_keywords))
            # name__表示在name上进行操作  name__icontains 做like语句操作 ---加i表示 不区分大小写


        # 排序
        sort = request.GET.get('sort','')
        if sort:
            if sort == "hot":
                all_orgs = all_teachers.order_by("-click_nums")  # 根据学习人数进行排名
        # 左侧栏 讲师排行榜
        sorted_teacher = Teacher.objects.all().order_by("-click_nums")[:3]
        # 对讲师进行分页
        # 分页 对讲师 看做对象然后进行分页
        try:
            # 生成页码时会自动加上page 无需做过多改动
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1

        p = Paginator(all_teachers, 3, request=request)   # 每页显示5个

        teachers = p.page(page)

        return render(request, "teachers-list.html", {
            "all_teachers":teachers,  # 传到 前台页面 然后使用objec_list进行分页
            "sort":sort,
            "sorted_teacher":sorted_teacher,
             # 可以向上传递 即可以传递到其所继承的base.html页面
        })


class TeacherDetailView(View):
    '''
    讲师详情
    '''
    def get(self, request, teacher_id):
        # url 中配置有 teacher/detail/id[0...]  因此要有teacher_id接收
        teacher = Teacher.objects.get(id=int(teacher_id))
        all_courses = Course.objects.filter(teacher=teacher) # 拿到该讲师的所有课程
        # 更新导师
        teacher.click_nums += 1
        teacher.save()

        # 更新收藏关系 即点击收藏讲师、机构后刷新页面能够同步显示收藏状态
        has_teacher_faved = False
        has_org_faved = False

        if not request.user.is_authenticated:
            if UserFavorite.objects.filter(user=request.user, fav_type=3, fav_id=teacher.id):  # 3代表讲师
                has_teacher_faved = True

            if UserFavorite.objects.filter(user=request.user, fav_type=2, fav_id=teacher.org.id):  # 3代表机构
                has_org_faved = True


        # 讲师排行
        sorted_teacher = Teacher.objects.all().order_by("-click_nums")[:3]
        return render(request, "teacher-detail.html", {
            "teacher":teacher,
            "all_courses":all_courses,
            "sorted_teacher":sorted_teacher,
            "has_teacher_faved":has_teacher_faved,
            "has_org_faved":has_org_faved,
        })